<template>
	<view class="container">
		<navView navTitle="项目进度" titleColor="#fff" :isBack="true"></navView>
		<view class="topbox">
			<!-- 项目名称区域 -->
			<view class="project-title">{{ project.name }}</view>
			<!-- 动态状态标题 -->
			<view class="status-tag" :class="'status'">项目状态：{{ project.contract_status == 0 ? '未开始' : project.contract_status == 1 ? '进行中' : project.contract_status
				== 2 ? '已完成' : '' }}</view>

			<!-- 进度条 -->
			<uni-section title="基本用法" type="line" padding>
				<uni-steps :options="steps" :active="activeIndex" />
			</uni-section>
			<view class="status-tag" :class="'status'">节点状态：{{ progress.is_over == 0 ? '未完成' : '已完成' }}</view>
		</view>
		<view class="content">
			<view class="tite">
				{{ progress.progress_name }}
			</view>
			<view class="data-statistics">
				<view class="title">
					<view class="tiao"></view>
					介绍
				</view>
				<view class="options">
					{{ progress.ass_desc }}
				</view>
			</view>
			<view class="data-statistics">
				<view class="title">
					<view class="tiao"></view>
					时间要求
				</view>
				<view class="times">
					<view class="time">
						<view class="name">
							开始时间
						</view>
						<view class="right">
							<!-- <view class="text">
								请选择
							</view> -->
							<!-- <uni-datetime-picker v-model="single">
								<uni-icons type="right"></uni-icons>
							</uni-datetime-picker> -->
							{{ project.start_time }}
						</view>
					</view>
					<view class="time">
						<view class="name">
							结束时间
						</view>
						<view class="right">
							<!-- <view class="text">
								请选择
							</view> -->
							<!-- <uni-datetime-picker v-model="single">
								<uni-icons type="right"></uni-icons>
							</uni-datetime-picker> -->
							{{ project.end_time }}
						</view>
					</view>
				</view>
			</view>
			<view class="data-statistics">
				<view v-if="progress.file_switch == 1">
					<view class="title">
						<view class="tiao"></view>
						附件材料
					</view>
					<view class="root">
						<view class="list-item" v-for="(item, index) in progress.files" :key="index">
							<image class="file-icon" src="https://hfd.bjlzkj.com/static/list/PDF.png" />
							<view class="option">
								<view class="file-info">
									<view class="file-title">{{ item.name }}</view>
									<view class="file-time"></view>
								</view>
								<view class="action-buttons">
									<button class="download-button" @click="handleDownload(item.url)">下载</button>
									<button class="view-button" @click="handleView(item.url)">查看</button>
								</view>
							</view>
						</view>
					</view>
					<button class="btn upload-btn" @click="uploadFile(true)">上传附件</button>
				</view>
				<view>
					<view class="title">
						<view class="tiao"></view>
						证明文件
					</view>
					<view class="root">
						<view class="list-item" v-for="(item, index) in progress.attachment" :key="index">
							<image class="file-icon" src="https://hfd.bjlzkj.com/static/list/PDF.png" />
							<view class="option">
								<view class="file-info">
									<view class="file-title">{{ item.name }}</view>
									<view class="file-time"></view>
								</view>
								<view class="action-buttons">
									<button class="download-button" @click="handleDownload(item.url)">下载</button>
									<button class="view-button" @click="handleView(item.url)">查看</button>
								</view>
							</view>
						</view>
					</view>
					<button class="btn upload-btn" @click="uploadFile()">上传附件</button>
				</view>
				<button v-if="progress.is_over == 0" class="btn complete-btn" @click="complete()">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
import download from '@/util/filesdownload.js'; //
export default {
	data() {
		return {
			steps: [], // 步骤数组
			activeIndex: 0, // 当前激活的步骤索引
			project: {},
			contractID: '',
			progress: {},
			fileSwitch: false,
			formData: {
				contract_id: '', // 关联id
				node_id: 0, // 节点id
				ass_desc: 0, // 描述1
				files: '', // 附件文件
				attachment: "", // 证明文件
				is_over: '', // 节点是否完成
			},
		};
	},
	onLoad(options) {
		this.contractID = options.id;
		this.getProjectProgress();
	},
	methods: {
		complete() {
			uni.showModal({
				title: '操作确认',
				content: '确认要完成该节点吗？完成后将不可修改',
				success: (res) => {
					if (res.confirm) {
						this.formData.contract_id = this.contractID;
						this.formData.node_id = this.project.progress[this.activeIndex].id;
						this.formData.ass_desc = this.project.progress[this.activeIndex].ass_desc;
						this.formData.is_over = 1;
						this.formData.files = ''; // 初始化
						this.formData.attachment = ''; // 初始化
						// 处理files（添加数组存在性校验）
						if (this.project.progress[this.activeIndex].files && this.project.progress[this.activeIndex].files.length > 0) {
							this.project.progress[this.activeIndex].files.forEach(item => {
								console.log(item)
								this.formData.files += item.localurl + ',';
							});
						}

						// 处理attachment（添加数组存在性校验）
						if (this.project.progress[this.activeIndex].attachment && this.project.progress[this.activeIndex].attachment.length > 0) {
							this.project.progress[this.activeIndex].attachment.forEach(item => {
								this.formData.attachment += item.localurl + ',';
							});
						}			
						
						this.$request('/addons/qingdong/contract/editProject', 'POST', this.formData).then(res => {
							if (res.code == 1) {
								uni.showToast({ title: '设置成功', icon: 'success' });  // 新增失败提示								
							}else{
								uni.showToast({ title: '设置失败', icon: 'fail' });
							}							
							this.getProjectProgress(); // 重新获取项目进度
						});
					}else{
						uni.showToast({ title: '已取消', icon: 'fail' });
					}
				}
			});
		},
		// 获取项目进度
		async getProjectProgress() {
			const res = await this.$request('/addons/qingdong/contract/getContractInfo', 'POST', { id: this.contractID }).then(res => {
				return res.data;
			})
			this.project = res
			this.updateStepsAndActiveIndex();
			// 新增：确保获取当前进度数据
			this.progress = this.getCurrentProgress();  // 添加这行this.getCurrentProgress();			
		},
		updateStepsAndActiveIndex() {
			if (this.project.progress) {
				this.steps = this.project.progress.map(item => ({
					title: item.progress_name,
					desc: item.acc_time
				}));
				// 找到第一个未完成的步骤
				this.activeIndex = this.project.progress.findIndex(item => item.is_over !== 1);
				if (this.activeIndex === -1) { // 如果所有的步骤都是已完成的，激活最后一个步骤
					this.activeIndex = this.steps.length - 1;
				}
			}
		},
		// 获取当前激活的进度数据
		getCurrentProgress() {
			if (this.project.progress && this.activeIndex !== -1) {
				return this.project.progress[this.activeIndex];
			}
			return null;
		},
		handleDownload(url) {
			download.downloadFun(url);
		},
		handleView(url) {
			// 检查文件是否已下载
			uni.showLoading({ title: '正在打开...' });  // 新增加载提示
			uni.downloadFile({
				url: url,
				success: function (res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: encodeURI(filePath),
						showMenu: true,
						success: function (res) {
							uni.hideLoading();  // 隐藏加载提示
							console.log('打开文档成功', res);
						},
						fail: function (err) {
							uni.hideLoading();  // 隐藏加载提示
							console.error('打开文档失败', err);
						}
					});
				},
				fail: (err) => {
					uni.hideLoading();  // 隐藏加载提示
					console.error('下载失败', err);
					uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
				}
			});
		},
		// 去上传按钮点击事件
		uploadFile(sw) {
			const token = uni.getStorageSync('user_token');
			uni.chooseImage({
				count: 9,
				type: 'all',
				success: async (res) => {
					const result = uni.uploadFile({
						url: 'https://hfd.bjlzkj.com/addons/qingdong/common/upload',
						filePath: res.tempFilePaths[0],  // 改用tempFilePaths数组中的路径
						name: 'file',  // 后端接收文件的参数名
						formData: {
							category: this.category,  // 添加分类参数
						},
						header: {
							'Content-Type': 'application/json',
							'token': token // 新增token请求头
						},
						success: (uploadFileRes) => {
							console.log('上传结果:', uploadFileRes);
							uni.showToast({ title: '上传成功' });
							// 新增数据解析校验
							try {
								const resData = JSON.parse(uploadFileRes.data);								
								if (resData && resData.data && resData.data.url) {
									if (sw) {
										this.$set(this.progress, 'files', [
											...(this.progress.files || []),
											{
												name: resData.data.url.split('/').pop(),
												url: resData.data.url,
												localurl: resData.data.flie_url
											}
										]);
									} else {
										this.$set(this.progress, 'attachment', [
											...(this.progress.attachment || []),
											{
												name: resData.data.url.split('/').pop(),
												url: resData.data.url,
												localurl: resData.data.flie_url
											}
										]);
									}
								} else {
									console.error('接口返回数据异常:', resData);
								}
							} catch (e) {
								console.error('数据解析失败:', e);
							}							
						},
						fail: (err) => {
							console.error('上传失败:', err);
							uni.showToast({ title: '上传失败', icon: 'none' });
						},
					})
				}
			});
		}
	},
};
</script>

<style lang="scss">
.container {
	padding: 20px;
}

.topbox {
	width: 100%;
	background: #fff;
	border-radius: 16rpx;
	padding: 20rpx;
	box-sizing: border-box;
	box-shadow: 0rpx 2rpx 12rpx 2rpx rgba(97, 97, 97, 0.25);

	.project-title {
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
	}

	.status-tag {
		display: block;
		width: fit-content;
		border-radius: 10rpx;
		padding: 6rpx 12rpx;
		font-size: 22rpx;
		margin: 10rpx auto;
		font-weight: bold;
		background-color: rgba(0, 122, 255, 0.1);
		color: #007aff;
	}
}

.content {
	.tite {
		font-size: 26rpx;
		color: #333333;
		font-weight: bold;
		line-height: 20rpx;
		margin: 40rpx 0;
	}

	.data-statistics {
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
		margin-bottom: 20rpx;

		.title {
			font-size: 28rpx;
			font-weight: bold;
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #ccc;
			padding: 24rpx 12rpx;

			.tiao {
				width: 6rpx;
				height: 22rpx;
				background: #1B87E8;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				margin-right: 10rpx;
			}
		}

		.times {
			padding: 10rpx 0rpx;

			.uni-icons {
				margin-right: 10rpx;
			}

			.time:first-child {
				border: 0;
			}

			.time {
				padding: 20rpx 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				color: #333333;
				font-size: 24rpx;
				border-top: 1rpx solid #ccc;

				.right {
					display: flex;
					align-items: center;
				}
			}
		}

		.btn {
			border-radius: 10rpx;
			/* 增大圆角 */
			border: 1rpx solid #008EFF;
			color: #008EFF;
			font-size: 26rpx;
			/* 增大字体 */
			background: transparent;
			padding: 15rpx 30rpx;
			/* 调整内边距 */
			transition: all 0.3s ease;
			/* 添加过渡效果 */
			margin-right: 15rpx;
			/* 添加按钮间距 */
			/* 新增 */
			margin: 20rpx auto 0;
			/* 修改 */
			width: 93%;
		}

		/* 上传附件按钮样式 */
		.upload-btn:hover {
			background-color: rgba(0, 142, 255, 0.1);
			border-color: #0077e6;
			align-self: flex-start; // 新增（左对齐）
			
		}

		/* 完成按钮样式 */
		.complete-btn {
			background-color: #008EFF;
			color: white;
			border: none;
			box-shadow: 0 4rpx 8rpx rgba(0, 142, 255, 0.3);
			margin-top: 10rpx;
			display: block;
			/* 新增 */
			margin: 20rpx auto 0;
			/* 修改 */
			width: 93%;
			/* 可选，控制按钮宽度 */
		}

		.complete-btn:hover {
			background-color: #0077e6;
			box-shadow: 0 6rpx 12rpx rgba(0, 142, 255, 0.4);
			transform: translateY(-2rpx);
		}
	}

	.options {
		font-weight: 400;
		font-size: 24rpx;
		color: #333333;
		padding: 20rpx;
		box-sizing: border-box;

	}

	.root {
		padding: 20rpx;
		display: flex; // 新增
		flex-direction: column; // 新增
		gap: 20rpx; // 新增
		.list-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			position: relative;
			justify-content: space-between;

			&:last-child {
				border: 0;
			}

			.file-icon {
				width: 120rpx;
				height: 120rpx;
			}

			.option {
				width: 80%;

				.file-info {
					flex: 1;

					.file-title {
						font-size: 24rpx;
						font-weight: bold;
						color: #333;
					}

					.file-time {
						font-size: 24rpx;
						color: #999;
						margin-top: 8rpx;
					}
				}

				.action-buttons {
					width: 100%;
					display: flex;
					justify-content: flex-end;
					margin-top: 20rpx;

					.download-button {
						width: 158rpx;
						height: 57rpx;
						border-radius: 58rpx 58rpx 58rpx 58rpx;
						border: 4rpx solid #008EFF;
						font-size: 20rpx;
						color: #008EFF;
						background: #fff;
						margin: 0;
					}

					.view-button {
						width: 158rpx;
						height: 57rpx;
						border-radius: 58rpx 58rpx 58rpx 58rpx;
						border: 4rpx solid #008EFF;
						font-size: 20rpx;
						color: #fff;
						background: #008EFF;
						margin: 0;
						margin-left: 20rpx;
					}
				}
			}
		}
	}
}
</style>